<?php

namespace app\admin\controller\formwork;

use app\common\controller\Backend;
use addons\wxsaas\library\Wechat;
use app\admin\model\Formwork as FormworkModel;
use app\admin\model\FormworkVersion as FormworkVersionModel;

/**
 * 模板版本管理
 */
class Wxtpl extends Backend
{

    //protected $relationSearch = true;
    //protected $searchFields = 'id,title';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('FormworkVersion');
    }

    /**
     * 查看
    */
    public function index()
    {
        if(get_addon_info('wxsaas')){
            //获取模板草稿
            $wx = new Wechat;
            if($draft_list = $wx->getTemplateDraftList()){
                for($n=0;$n<sizeof($draft_list);$n++){
                    //查询模板草稿是否已经在模板库中
                    if(!$version = FormworkVersionModel::getDraftId($draft_list[$n]['draft_id'])){
                        //把草稿添加到模板库
                        $result = $wx->addToTemplate($draft_list[$n]['draft_id']);
                        if($result['errcode'] == 0){
                            //获取模板列表
                            if($template = $wx->getTemplateList()){
                                $version = new FormworkVersionModel;
                                $version->save([
                                    'template_id' => $template[0]['template_id'],
                                    'draft_id' => $draft_list[$n]['draft_id'],
                                    'version' => $draft_list[$n]['user_version'],
                                    'desc' => $draft_list[$n]['user_desc']
                                ]);
                            }
                        }
                    }
                }
            }   
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('show',1)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
   
   /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new FormworkModel;
        $list = $model->getApiList();
        $this->assign("list", $list);
        return parent::edit($ids);
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $templateIds = $this->model->where('id', 'in', $ids)->column('template_id');
            //删除微信端模板
            $wx = new Wechat;
            $wx->deleteTemplateAll($templateIds);
            $attachmentlist = $this->model->where('id', 'in', $ids)->update(['show'=>0]);
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
